# ~*~ coding: utf-8 ~*~
import time

from apps.common.dbbase import BaseModel
from apps.common.utils import generate_uuid
from apps.extensions import db
from sqlalchemy.dialects.mysql import TINYINT

__all__ = ['Project', 'Server', 'Permission']


class Project(BaseModel):
    # 表的名字:
    __tablename__ = 'codes_project'

    STATUS_CLOSE = 0    # 已激活
    STATUS_OPEN = 1     # 未激活

    TASK_AUDIT_DISABLE = 0
    TASK_AUDIT_ENABLE = 1

    REPO_MODE_BRANCH = 'branch'
    REPO_MODE_TAG = 'tag'

    REPO_TYPE_GIT = 'git'
    REPO_TYPE_SVN = 'svn'

    LINE_SPILT_CHAR = "\r\n"

    id = db.Column(db.CHAR(36), default=generate_uuid, primary_key=True)
    # 项目名称
    name = db.Column(db.VARCHAR(255), unique=True)
    # 所属环境
    environment_id = db.Column(db.CHAR(36))
    # 仓库相关信息
    repo_url = db.Column(db.VARCHAR(128))
    repo_username = db.Column(db.VARCHAR(128), nullable=True)
    repo_password = db.Column(db.VARCHAR(128), nullable=True)
    repo_mode = db.Column(db.VARCHAR(32), default=REPO_MODE_TAG)
    repo_type = db.Column(db.VARCHAR(32), default=REPO_TYPE_SVN)

    # 目标主机的web目录
    target_root = db.Column(db.VARCHAR(200))
    # 目标主机的release目录
    target_releases = db.Column(db.VARCHAR(200))
    # 自定义的变量
    vars = db.Column(db.Text, nullable=True)

    # 保留的版本数
    keep_version_num = db.Column(TINYINT, default=10)
    # 部署之前
    prev_deploy = db.Column(db.Text, nullable=True)
    # 部署之后
    post_deploy = db.Column(db.Text, nullable=True)
    # 释放之前
    prev_release = db.Column(db.Text, nullable=True)
    # 释放之后
    post_release = db.Column(db.Text, nullable=True)
    # 是否开启审核 1: 审核 0: 不审核,
    task_audit = db.Column(TINYINT, default=TASK_AUDIT_DISABLE)
    # 是否启用 1: 激活, 0: 未激活
    status = db.Column(db.Integer, default=STATUS_OPEN)
    # 项目描述信息
    describe = db.Column(db.TEXT, default='')

    # 标签
    label_id = db.Column(db.CHAR(36))
    # 该项目的权限用户
    privilege_user = db.Column(db.CHAR(36))
    # 只上线指定目录中的内容
    sparse_dir = db.Column(db.CHAR(128), default='')

    create_by = db.Column(db.VARCHAR(32), nullable=True)
    create_time = db.Column(db.INT, default=time.time)
    update_time = db.Column(db.INT, default=time.time, onupdate=time.time)

    @property
    def short_id(self):
        return str(self.id).split('-')[-1]

    def __str__(self):
        return '<Project: {}>'.format(self.name)


class Server(BaseModel):
    # 表的名字:
    __tablename__ = 'codes_server'

    id = db.Column(db.CHAR(36), default=generate_uuid, primary_key=True)
    # 服务器
    asset_id = db.Column(db.CHAR(36), nullable=True)
    # 所属的项目
    project_id = db.Column(db.CHAR(36), nullable=True)


class Permission(BaseModel):
    # 表的名字:
    __tablename__ = 'codes_permission'

    id = db.Column(db.CHAR(36), default=generate_uuid, primary_key=True)
    # 项目
    project_id = db.Column(db.CHAR(36), nullable=True)
    # 用户
    user_id = db.Column(db.CHAR(36), nullable=True)


